import Vue from 'vue'
import Vuex from 'vuex'
// import * as actions from './actions'
// import * as getters from './getters'
import axios from 'axios';
import { rsort } from 'semver';

import { getsdecimal } from '@/api/api'
import { name } from 'file-loader';

Vue.use(Vuex)


const store = new Vuex.Store({
    state: {
        decimal: 0,
        count: 10,
        shopchar: [1, 2, 3],
        obj: {},
        data: null,
        websocketData: [],
        websocketDataps: {}
    },

    mutations: {
        sum(state, obj) {
            let { num, age } = obj
            state.count = state.count + num
        },
        setData(state, data) {
            state.data = data
        },

        // 结构科学计数法
        c(state, param) {
            let strParam = String(param)
            let flag = /e/.test(strParam)
            if (!flag) state.decimal = param
            // 指数符号 true: 正，false: 负
            let sysbol = true
            if (/e-/.test(strParam)) {
                sysbol = false
            }
            // 指数
            let index = Number(strParam.match(/\d+$/)[0])
            // 基数
            let basis = strParam.match(/^[\d\.]+/)[0].replace(/\./, '')
            if (sysbol) {
                state.decimal = basis.padEnd(index + 1, 0)
            } else {
                state.decimal = basis.padStart(index + basis.length, 0).replace(/^0/, '0.')
            }
        },
        // 设置websocketData
        setwebsocketData(state, data) {
            state.websocketData = data
        },
        // 设置websocketDataps key
        websocketDatapskey(state, data) {
            let key = data.name;
            let value = data.item;
            let obj = {};
            obj[key] = value;
            //  state.websocketDataps[data.name] = data
            state.websocketDataps = Object.assign({},state.websocketDataps, obj);
         },
        // 设置websocketDataps id 价格
        websocketDatapsidPrice(state, data) {
            let name = data['name']
            state.websocketDataps[name]['s2'] = data['s2']
            state.websocketDataps[name]['b1'] = data['b1']
            state.websocketDataps[name]['a'] = data['a']
          
        },
    },
    getters: {
        upMyinfo: (state) => (obj) => { //修改
            return state.obj = obj
        },
        getMyinfo(state) { //取出
            console.log(state)
            return state.count;
        }
    },
    actions: {
        // 科学计数法转化数组
        getsdecimallength(ctx) {
            let decimalparams = {
                platform: 'real',
                needThreeMoth: 'false'
            }
            getsdecimal(decimalparams, '/market/v2/product').then(res => {
                if (res.status == 200) {
                    let data = res.data
                    let id = 0
                    let websocketData = []
                    for (let i = 0; i < data.length; i++) {
                        for (let j = 0; j < data[i]['list'].length; j++) {
                            id++
                            let p_item = data[i].list[j];
                            let item = { id: id, s2: 0, b1: 0, decimal: 0, a: 0 };
                            data[i]['list'][j]['id'] = id
                            websocketData.push(data[i]['list'][j])
                            let PriceChanges = data[i]['list'][j]['minPriceChanges']
                            if (PriceChanges) {
                                ctx.commit('c', PriceChanges)
                                //   在action中获取state
                                PriceChanges = ctx.state.decimal
                                if (PriceChanges.indexOf('.') >= 0) {
                                    PriceChanges = PriceChanges.split(".")[1];
                                    PriceChanges = PriceChanges.length
                                } else {
                                    PriceChanges = PriceChanges.length
                                }
                            } else {
                                PriceChanges = 2;
                            }

                            item.decimal = PriceChanges
                            let name = p_item.feed_code
                            let obj = {
                                name,
                                item
                            }
                            ctx.commit('websocketDatapskey', obj)
                        }
                    }
                    ctx.commit('setwebsocketData', websocketData)
                    ctx.dispatch('WebSocketTest')
                }
            })
        },

        WebSocketTest(ctx) {
            var ws;
            if ("WebSocket" in window) {
                ws = new WebSocket("wss://mihuiapi.com/cuws");
                ws.onopen = function () {
                    ws.send(JSON.stringify({ op: 'auth', args: 'hkcuqwert!@#$' }));
                };
                ws.onmessage = function (evt) {
                    let received_msg = JSON.parse(evt.data);
                    for (let i = 0; i < received_msg.length; i++) {
                        if (received_msg[i]['op'] == 'orderBookL1') {
                            let name = received_msg[i]['data']['p']
                            let b1 = received_msg[i]['data']['b1']
                            let s2 = received_msg[i]['data']['s2']
                            let a = received_msg[i]['data']['a']
                            let existence = ctx.state.websocketDataps
                            if (existence[name]) {
                                let decimal = existence[name]['decimal']
                                let data = {
                                    name: name,
                                    b1: b1.toFixed(decimal),
                                    s2: s2.toFixed(decimal),
                                    a: a
                                }
                                ctx.commit('websocketDatapsidPrice', data)
                            }
                        }
                    }
                };
                ws.onclose = function () {
                    setTimeout(()=>{
                        ctx.dispatch('WebSocketTest')
                    },5000)
                 };
            } else {
                alert("您的浏览器不支持 WebSocket!");
            }
        },




        setNodelist(ctx, payload) {
            // let {topice,topiceDetaile} = payload
            //     console.log(topice,topiceDetaile)
            //     axios(`https://cnodejs.org/api/v1${topice}`).then(res => {
            //     if(res.status ==200){
            //         var data=res.data.data
            //         console.log(data)
            //         ctx.commit('setData',data)
            //     }

            // })
        }
    }

})
// 应用初始状态
// const state = {
//     count: 10
// }

// // 定义所需的 mutations
// const mutations = {
//     INCREMENT(state) {
//         state.count++
//     },
//     DECREMENT(state) {
//         state.count--
//     }
// }

// 创建 store 实例
// export default new Vuex.Store({
//     actions,
//     getters,
//     state,
//     mutations
// })
export default store